package net.wanho.zaixian.cms.service.impl;

import net.wanho.zaixian.cms.dao.CmsTemplateDao;
import net.wanho.zaixian.cms.service.CmsTemplateService;
import net.wanho.zaixian.pojo.cms.CmsTemplate;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CmsTemplateServiceImpl implements CmsTemplateService {

    @Resource
    private CmsTemplateDao cmsTemplateDao;

    @Resource
    private GridFsTemplate gridFsTemplate;

    /**
     * 查询所有的模板
     * @return
     */
    @Override
    public List<CmsTemplate> getAllTemplate() {
        List<CmsTemplate> cmsTemplateList = cmsTemplateDao.findAll();
        return cmsTemplateList;
    }

    @Override
    public CmsTemplate getTemplateById(String templateId) {
        Optional<CmsTemplate> byId = cmsTemplateDao.findById(templateId);
        CmsTemplate cmsTemplate = byId.get();
        return cmsTemplate;
    }

    /**
     * 模板文件上传
     */
    @Override
    public String templateUpload(Object object) throws UnsupportedEncodingException {
        Map<String,String> map = (Map<String,String>)object;
        System.out.println(map);
        String htmlValue = map.get("htmlValue");
        String templateName=map.get("templateName");
        String siteId = map.get("siteId");
        System.out.println(htmlValue);
        System.out.println(templateName);
        InputStream is = new ByteArrayInputStream(htmlValue.getBytes("UTF-8"));
        //向GridFS存储文件
        ObjectId objectId = gridFsTemplate.store(is, templateName, "text");
        //得到文件ID
        String fileId = objectId.toString();
        CmsTemplate cmsTemplate = new CmsTemplate();
        cmsTemplate.setTemplateFileId(fileId);
        cmsTemplate.setTemplateName(templateName);
        cmsTemplate.setSiteId(siteId);
        insertCmsTemplate(cmsTemplate);
        return fileId;
    }

    /**
     * 将上传的文件信息添加到cmsTemplate表中
     */
    @Override
    public void insertCmsTemplate(CmsTemplate cmsTemplate) {
       cmsTemplateDao.insert(cmsTemplate);
    }
}
